package com.qfjy.project.weixin.api.userinfo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfjy.entity.Weiuser;
import com.qfjy.project.weixin.api.accessToken.AccessTokenRedis;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserInfoUtil {
  private  static String  WEIXIN_API_USER_INFO_GET="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    /**
     * 收集微信个人信息，并存入数据库weiuser表中
     * @param openid
     */
    @Autowired
    private AccessTokenRedis accessTokenRedis;
    @Resource
    private WeiUserService weiUserService;
   public void userInfoService(String openid)  {
      // Weiuser weiuser = weiUserService.selectWeiUserByOpenid(openid);
        if(redisSetOpenidHash(openid)==false){
            JSONObject weiXinApi = this.getWeiXinApi(openid);
            Weiuser weiuser1 = this.convertJsonToWeiUser(weiXinApi);

            weiUserService.insertSelective(weiuser1);
            this.redisSetOpenid(openid);
        }else {
            //更新
//            JSONObject weiXinApi = this.getWeiXinApi(openid);
//            Weiuser weiuser1 = this.convertJsonToWeiUser(weiXinApi);

        }

   }





    public JSONObject getWeiXinApi(String openid){
        String url=WEIXIN_API_USER_INFO_GET.replace("ACCESS_TOKEN",accessTokenRedis.getAccessTokenVal()).replace("OPENID",openid);
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
        log.info(jsonObject.toString());
        return jsonObject;
    }


    public Weiuser convertJsonToWeiUser(JSONObject jsonObject) {

        ObjectMapper objectMapper=new ObjectMapper();
        Weiuser weiuser=null;
        try {
             weiuser = objectMapper.readValue(jsonObject.toString(), Weiuser.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return weiuser;
    }
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

   private static final String WEIUSER_OPENID="weiuser:openid:list";
    /**
     * 收集openid
     */
    public void redisSetOpenid(String openid){
        redisTemplate.opsForSet().add(WEIUSER_OPENID,openid);

    }
   public boolean redisSetOpenidHash(String openid){
       Boolean member = redisTemplate.opsForSet().isMember(WEIUSER_OPENID, openid);
       return member;
   }
}